package com.example.gw_back_end.utils;

import com.example.gw_back_end.config.MinioConfig;
import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Component
public class MinioUtil {

    private final MinioConfig minioConfig;
    private final MinioClient minioClient;
    private final String tempBucket;

    public MinioUtil(MinioConfig minioConfig, MinioClient minioClient) {
        this.minioConfig = minioConfig;
        this.minioClient = minioClient;
        this.tempBucket = minioConfig.getTempBucketName(); // 初始化逻辑移至构造方法
    }

    private static final Object fileLock = new Object(); // 锁对象

    // 存储文件
    public String upload(MultipartFile file) {

//        String newFileName;
//        String suffix;
//
//        // 同步生成文件名
//        synchronized (fileLock) {
//            newFileName = UUID.randomUUID().toString().replaceAll("-", "");
//            String originalFileName = file.getOriginalFilename();
//            suffix = (originalFileName != null) ?
//                    originalFileName.substring(originalFileName.lastIndexOf(".")) : "";
//        }

        String newFileName = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFileName = file.getOriginalFilename();
        String suffix = null;
        if (originalFileName != null) {
            suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        try {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(tempBucket).build());
            if (!found) {
                createBucket(tempBucket);
            }
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(tempBucket).object(newFileName + suffix)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            minioClient.putObject(objectArgs);
            return minioConfig.getEndpoint() + "/" + tempBucket + "/" + newFileName + suffix;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 创建存储桶
    public void createBucket(String bucketName){
        try {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 清空存储桶
    public boolean clearBucket(String bucketName){
        try {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (found) {
                Iterable<Result<Item>> allObj = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
                List<DeleteObject> objList = new ArrayList<>();
                for (Result<Item> result : allObj) {
                    Item item = result.get();
                    objList.add(new DeleteObject(item.objectName()));
                }
                RemoveObjectsArgs removeObjectsArgs = RemoveObjectsArgs.builder().bucket(bucketName).objects(objList).build();
                Iterable<Result<DeleteError>> results = minioClient.removeObjects(removeObjectsArgs);
                for (Result<DeleteError> result : results) {
                    DeleteError error = result.get();
                    if (error != null) {
                        System.out.println("Error in deleting object " + error.objectName() + "; Error: " + error.message());
                    }
                }
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 删除存储桶中的存储对象
    public boolean deleteBucketObj(String bucketName,String fileName){
        if (bucketName == null || bucketName.trim().isEmpty()) {
            throw new IllegalArgumentException("Bucket name cannot be null or empty.");
        }
        if (fileName == null || fileName.trim().isEmpty()) {
            throw new IllegalArgumentException("File path cannot be null or empty.");
        }
        try {
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build();
            minioClient.removeObject(removeObjectArgs);
            return true;
        } catch ( Exception e ) {
            throw new RuntimeException(e);
        }
    }

    // 删除存储桶
    public boolean deleteBucket(String bucketName){
        if (bucketName == null || bucketName.trim().isEmpty()) {
            throw new IllegalArgumentException("Bucket name cannot be null or empty.");
        } else {
            try {
                minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
                return true;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
